/**
 * 
 */
package pe.bf.extranet.web.utils;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;

/**
 *  
 *
 */
public final class ExportExcel<T> {

	/**
	 * 
	 */
	public ExportExcel() {
		// TODO Auto-generated constructor stub
	}
	
	
	public void generarExcel(HttpServletRequest request,
			HttpServletResponse response,List<T> list,String fileName,String templateName,String aliasList) throws Exception,
			InvalidFormatException, FileNotFoundException {
		String path = request.getServletContext().getRealPath("/plantillasxls/"+templateName);
		InputStream is = new BufferedInputStream(new FileInputStream(path));
        
		Map beans = new HashMap();
        beans.put(aliasList, list);
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        beans.put("dateFormat", dateFormat);
        beans.put("decimalFormat", decimalFormat);

        XLSTransformer transformer = new XLSTransformer();
        HSSFWorkbook resultWorkbook = (HSSFWorkbook) transformer.transformXLS(is, beans);
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", 
        	    "attachment; filename="+fileName+".xls");
        ServletOutputStream out = response.getOutputStream();
        byte[] bytes=resultWorkbook.getBytes();
        out.write(bytes, 0, bytes.length);
        out.close();
        
	}
	

}
